#pragma once

#include "Sock.hpp"
#include <sys/select.h>

using namespace std;

const uint16_t defaultport = 8888;
const int fd_max_num = (sizeof(fd_set) * 8);
const int defaultfd = -1;

class SelectServer
{
public:
    SelectServer(uint16_t port = defaultport)
        : _port(port)
    {
        for (int i = 0; i < fd_max_num; i++)
        {
            fd_array[i] = defaultfd;
        }
    }
    ~SelectServer()
    {
        _listensock.Close();
    }

    bool Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();

        return true;
    }

    void Accepter()
    {
        // 监听事件就绪可以获取连接了
        uint16_t clientport;
        string clientip;
        int sock = _listensock.Accept(&clientip, &clientport);
        if (sock < 0)
            return;
        cout << "accept success ,fd:" << sock << ",clientip:" << clientip << ",clientport:" << clientport << endl;

        // 可以直接读取吗，不可以，读取事件没就绪，还需要把sock放入到select中
        int pos = 1;
        for (; pos < fd_max_num; pos++)
        {
            if (fd_array[pos] != defaultfd)
                continue;
            else
                break;
        }
        // 出循环有2个原因，1.等于defaultfd 2.pos =fd_max_num
        if (pos == fd_max_num)
        {
            cout << "server is full ,close fd:" << sock << endl;
            close(sock);
        }
        else
        {
            fd_array[pos] = sock;
            // 打印所有事件
            PrintFd();
        }
    }

    void Recver(int fd, int pos)
    {
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "get a message: " << buffer << endl;
        }
        else if (n == 0)
        {
            cout << "sockfd close ,fd:" << fd << endl;
            close(fd);
            fd_array[pos] = defaultfd; // 本质从select中移除
        }
        else
        {
            cout << "read failed ,fd:" << fd << endl;
            close(fd);
            fd_array[pos] = defaultfd;
        }
    }
    void Dispatcher(fd_set &rfds)
    {
        // 遍历fd_array，看哪个fd的事件就绪
        for (int i = 0; i < fd_max_num; i++)
        {
            int fd = fd_array[i];
            if (fd == defaultfd)
                continue;

            // 有两个事件1.监听事件就绪 2.读事件就绪
            if (FD_ISSET(fd, &rfds))
            {
                // 处理监听就绪事件
                if (fd == _listensock.Fd())
                {
                    Accepter(); // 连接管理器
                }
                // 读事件就绪
                else
                {
                    Recver(fd, i);
                }
            }
        }
    }

    void PrintFd()
    {
        cout << "online fd list : ";
        for (int i = 0; i < fd_max_num; i++)
        {
            if (fd_array[i] != defaultfd)
                cout << fd_array[i] << " ";
        }
        cout << endl;
    }

    void Start()
    {
        int listensock = _listensock.Fd();
        fd_array[0] = listensock;
        while (1)
        {
            // accept?不能直接accept！检测并获取listensock上面的事件，新连接到来，等价于读事件就绪
            // struct timeval timeout = {1, 0}; // 输入输出，可能要进行周期的重复设置

            // 如果事件就绪，上层不处理，select会一直通知你！
            // select告诉你就绪了，接下来的一次读取，我们读取fd的时候，不会被阻塞
            // rfds: 输入输出型参数。 1111 1111 -> 0000 0000

            fd_set rfds;
            FD_ZERO(&rfds);

            int maxfd = listensock;
            // 所有套接字都需要被select
            for (int i = 0; i < fd_max_num; i++)
            {
                if (fd_array[i] == defaultfd)
                    continue;
                else
                    FD_SET(fd_array[i], &rfds);
                if (maxfd < fd_array[i])
                {
                    maxfd = fd_array[i];
                    cout << "maxfd update,maxfd = " << maxfd << endl;
                }
            }

            struct timeval timeout = {0, 0}; // 输入输出，可能要进行周期的重复设置
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, nullptr);
            switch (n)
            {
            case 0:
                cout << "time out,timeval:" << timeout.tv_sec << "." << timeout.tv_usec << endl;
                break;
            case -1:
                cout << "select error" << endl;
                break;
            default:
                cout << "get a link !!!" << endl;
                Dispatcher(rfds);
                break;
            }
        }
    }

private:
    Sock _listensock;
    uint16_t _port;
    int fd_array[fd_max_num];
};